import React, { Component } from 'react';
import CustomForm from '../../../components/CustomForm';
import { Input, message, Select } from 'antd';
import userStorage from '../../../utils/storage';
import services from '../../../services/api';
import { getEncryptCode } from '../../../utils/utils';
import DeptSelect from '../../../components/DeptSelect';
import storage from '../../../utils/storage';

class UserAdd extends Component {
  constructor(props) {
    super(props);
    this.state = {
      treeData: [],
      detail: {},
      roles: [],
      confirmPwdRequired: false,
      applications: [],
    };
    this.actionType = this.props.actionType || 'add';
    this.form = null;
    this.api = 'user';
  }

  componentDidMount() {
    this.getDeptTree();
    this.getRoles();
    // 修改密码页面
    if (this.props.location.pathname === '/config/changePwd') {
      this.actionType = 'update';
      this.username = userStorage.userInfo.username;
      this.api = 'pwdConfig';
      this.getDetail();
    }
    if (this.actionType === 'add') {
      this.getApp(storage.dept);
    } else {
      this.name = this.props.record.name;
      this.getDetail();
    }
  }

  // 部门列表
  getDeptTree = () => {
    services.dept.tree().then((res) => {
      if (res.code === 0) {
        this.setState({ treeData: res.data });
      }
    });
  };

  // 渠道列表
  getApp = (dept_id) => {
    services.application.getDeptApp({ dept_id }).then((res) => {
      if (res.code === 0) {
        this.setState({ applications: res.data });
      }
    });
  };

  // 改变部门的回调
  deptChangeHandle(dept_id) {
    this.getApp(dept_id);
    this.form.setFieldsValue({ app_ids: [] }); // 清空事件
  }

  /**角色 */
  getRoles = () => {
    services.role.all().then((res) => {
      if (res.code === 0) {
        this.setState({
          roles: res.data,
        });
      } else {
        message.error(res.msg);
      }
    });
  };

  /**获取详情 */
  getDetail = () => {
    services[this.api].queryOne({ user_id: this.props.record.id }).then((data) => {
      if (data.code === 0) {
        this.setState({
          detail: data.data,
        });
        this.getApp(data.data.belonging_dept);
        this.form.setFieldsValue({
          name: data.data.name,
          username: data.data.username,
          email: data.data.email,
          mobile: data.data.mobile,
          remark: data.data.remark,
          role_ids: data.data.role_ids,
          belonging_dept: data.data.belonging_dept,
          app_ids: [...[], ...data.data.app_ids],
        });
      } else {
        message.error(data.msg);
      }
    });
  };

  // 搜索遍历
  getCode = (data, value) => {
    let node = '';
    for (let i = 0; i < data.length; i++) {
      if (data[i].dept_id === value) {
        node = data[i];
        break;
      } else {
        if (data[i].child) {
          node = this.getCode(data[i].child, value);
          if (node) break;
        }
      }
    }
    return node;
  };

  handleSubmit = () => {
    this.form.validateFields((err, values) => {
      if (!err) {
        const params = {
          name: values.name,
          username: values.username,
          email: values.email,
          mobile: values.mobile,
          remark: values.remark,
          role_ids: values.role_ids,
          app_ids: values.app_ids,
        };
        if (this.actionType === 'update') {
          params.id = this.state.detail.id;
          if (values.password && values.retype_password) {
            params.password = getEncryptCode(values.password);
            params.retype_password = getEncryptCode(values.retype_password);
          }
        } else if (this.actionType === 'add') {
          console.log(values);
          params.password = getEncryptCode(values.password);
          params.retype_password = getEncryptCode(values.retype_password);
          params.dept_id = values.belonging_dept;
          params.dept_code = (this.getCode(this.state.treeData, values.belonging_dept) || {}).dept_code;
        }

        services[this.api][this.actionType](params).then((data) => {
          if (data.code === 0) {
            message.success(data.msg);
            if (this.props.closeModal) {
              this.props.closeModal();
            }
          } else {
            message.error(data.msg);
          }
        });
      }
    });
  };

  handleConfirmBlur = (e) => {
    const { value } = e.target;
    this.setState({ confirmDirty: this.state.confirmDirty || !!value });
  };

  compareToFirstPassword = (rule, value, callback) => {
    if (value && value !== this.form.getFieldValue('password')) {
      callback('两次输入密码不一致');
    } else {
      callback();
    }
  };

  validateToNextPassword = (rule, value, callback) => {
    if (value && this.state.confirmDirty) {
      this.form.validateFields(['retype_password'], { force: true });
    }
    callback();
  };

  handleFirstPwd = (value) => {
    this.form.getFieldValue(['retype_password']);
    if (value) {
      this.setState({
        confirmPwdRequired: true,
      });
    } else {
      this.setState({
        confirmPwdRequired: false,
      });
    }
  };

  // 存在全部选项的多选Select
  formChangeIsAll = (value, code, name) => {
    if (value[value.length - 1] === code) {
      window.setTimeout(() => {
        this.form.setFieldsValue({ [name]: [code] });
      }, 0);
    } else {
      if (value.includes(code)) {
        window.setTimeout(() => {
          this.form.setFieldsValue({ [name]: value.filter((item) => item !== code) });
        }, 0);
      }
    }
  };

  render() {
    this.actionType = this.props.actionType;
    const { name, username, email, mobile, password, retype_password, remark, role_ids, belonging_dept } =
      this.props.record || {};
    const { roles, treeData, applications } = this.state;
    const formItems = [
      {
        label: {
          label: '用户名',
          className: 'tantuer-form-item2 tantuer-form-item-nowrap',
        },
        name: 'username',
        options: {
          initialValue: username,
          rules: [
            { required: true, message: '请输入姓名' },
            { max: 128, message: '最长128个字符' },
            { pattern: /^[\u4E00-\u9FA5_a-zA-Z0-9]+$/, message: '限中英文数字下划线' },
          ],
        },
        component: <Input placeholder='姓名' disabled={this.actionType === 'update'} autoComplete='off' />,
      },
      {
        label: {
          label: '员工姓名',
          className: 'tantuer-form-item2 tantuer-form-item-nowrap',
        },
        name: 'name',
        options: {
          initialValue: name,
          rules: [
            { required: true, message: '请输入姓名' },
            { max: 128, message: '最长128个字符' },
            { pattern: /^[\u4E00-\u9FA5_a-zA-Z0-9]+$/, message: '限中英文数字下划线' },
          ],
        },
        component: <Input placeholder='姓名' disabled={this.actionType === 'update'} />,
      },
      {
        label: {
          label: '邮箱',
          className: 'tantuer-form-item2 tantuer-form-item-nowrap',
        },
        name: 'email',
        options: {
          initialValue: email,
          rules: [{ type: 'email', message: '邮箱格式错误' }],
        },
        component: <Input placeholder='邮箱' disabled={this.actionType === 'update'} />,
      },
      {
        label: {
          label: '手机号',
          className: 'tantuer-form-item2 tantuer-form-item-nowrap',
        },
        name: 'mobile',
        options: {
          initialValue: mobile,
          rules: [{ pattern: /^\d{11}$/, message: '请输入正确的手机号' }],
        },
        component: <Input placeholder='手机号' disabled={this.actionType === 'update'} />,
      },

      {
        label: {
          label: '密码',
          className: 'tantuer-form-item2 tantuer-form-item-nowrap',
        },
        name: 'password',
        options: {
          initialValue: password,
          rules: [
            this.actionType !== 'update' ? { required: true, message: '请输入密码' } : false,
            { min: 6, message: '最小6个字符' },
            { max: 32, message: '最长32个字符' },
            {
              validator: this.validateToNextPassword,
            },
          ].filter(Boolean),
        },
        component: (
          <Input.Password
            placeholder='密码'
            autoComplete='new-password'
            disabled={this.actionType === 'update'}
            onChange={(e) => {
              return this.actionType === 'update' ? this.handleFirstPwd(e.target.value) : null;
            }}
          />
        ),
      },
      {
        label: {
          label: '确认密码',
          className: 'tantuer-form-item2 tantuer-form-item-nowrap',
        },
        name: 'retype_password',
        options: {
          initialValue: retype_password,
          rules: [
            this.actionType !== 'update' || this.state.confirmPwdRequired
              ? { required: true, message: '请确认密码' }
              : false,
            { min: 6, message: '最小6个字符' },
            { max: 32, message: '最长32个字符' },
            {
              validator: this.compareToFirstPassword,
            },
          ].filter(Boolean),
        },
        component: (
          <Input.Password
            placeholder='确认密码'
            onBlur={this.handleConfirmBlur}
            disabled={this.actionType === 'update'}
          />
        ),
      },
      {
        label: {
          label: '角色',
          className: 'tantuer-form-item2 tantuer-form-item-nowrap',
        },
        name: 'role_ids',
        options: {
          initialValue: role_ids,
          rules: [{ required: true, message: '请设置角色' }],
        },
        component: (
          <Select
            style={{ width: '100%' }}
            mode='multiple'
            onChange={(value) => this.formChangeIsAll(value, 94, 'role_ids')}
            showArrow={true}
          >
            {roles.map((it) => {
              return (
                <Select.Option value={it.id} key={it.name}>
                  {it.name}
                </Select.Option>
              );
            })}
          </Select>
        ),
      },
      DeptSelect({
        // treeCheckable: true, // 是否多选
        // treeCheckStrictly: true, // 多选时是否取消父子关联
        deptTree: treeData, // 全部部门数据
        deptArr: belonging_dept || storage.dept, // 当前部门数据
        // hasRight: true, // 是否需要权限展示
        nodeDisabled: (item) => !item.dept_id, // 节点禁选
        disabled: true,
        layout: {
          label: '所属部门',
          className: 'tantuer-form-item2 tantuer-form-item-nowrap',
        },
        rules: [{ required: true, message: '请选择所属部门' }],
        name: 'belonging_dept',
        onChange: (value) => this.deptChangeHandle(value),
      }),
      {
        label: {
          label: '渠道权限',
          className: 'tantuer-form-item2 tantuer-form-item-nowrap',
        },
        name: 'app_ids',
        options: {
          initialValue: [-1],
          rules: [{ required: true, message: '请选择渠道权限' }],
        },
        component: (
          <Select mode='multiple' onChange={(value) => this.formChangeIsAll(value, -1, 'app_ids')}>
            {applications.map((it) => {
              return (
                <Select.Option value={it.app_id} key={it.app_id}>
                  {it.app_name}
                </Select.Option>
              );
            })}
          </Select>
        ),
      },
      {
        label: {
          label: '备注',
          className: 'tantuer-form-item2 tantuer-form-item-nowrap',
        },
        name: 'remark',
        options: {
          initialValue: remark,
          rules: [{ max: 256, message: '最长256个字符' }],
        },
        component: <Input placeholder='备注' />,
      },
    ].filter(Boolean);

    return (
      <CustomForm
        {...this.props}
        closeModal={this.props.closeModal}
        colNum={1}
        createForm={(ref) => (this.form = ref)}
        formItems={formItems}
        onHandleSubmit={this.handleSubmit}
      />
    );
  }
}

export default UserAdd;
